package cn.rui.service.exam;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.exam.QuestionMapper;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.exam.ExamQuestion;
import cn.rui.pojo.User;
import cn.rui.pojo.vo.PageVo;
import cn.rui.pojo.vo.QuestionVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author 徽州大都督
 * @date 2021/6/24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserMapper userMapper;

    public ResponseBean findPage(PageVo pageVo, HttpSession session) {
        QueryWrapper<ExamQuestion> wrapper = new QueryWrapper<> ();
        Page<ExamQuestion> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());

        if (StrUtil.isNotEmpty (pageVo.getQueryContent ())) {
            wrapper.like ("question_content", pageVo.getQueryContent ());
        }

        if (!ObjectUtil.isEmpty (pageVo.getCategoryId ())) {
            wrapper.eq ("question_type", pageVo.getCategoryId ());
        }

        wrapper.orderByDesc ("create_time");

        IPage<ExamQuestion> questionIPage = questionMapper.selectPage (page, wrapper);

        PageVo pv = new PageVo ();

        pv.setTotal (questionIPage.getTotal ());

        List<ExamQuestion> questionList = questionIPage.getRecords ();

        for (ExamQuestion examQuestion : questionList) {
            User user = userMapper.selectById (examQuestion.getUserId ());
            examQuestion.setUser (user);
        }

        pv.setData (questionList);

        return ResponseBean.success (ContentBean.QuerySuccess, pv);
    }

    public ResponseBean deleteById(Long id) {
        questionMapper.deleteById (id);
        return ResponseBean.success (ContentBean.DeleteSuccess);
    }

    public ResponseBean save(ExamQuestion examQuestion, HttpSession session) {
        //添加多选题
        if (examQuestion.getQuestionType () == 2) {
            Set<String> selectAnswerList = examQuestion.getSelectAnswerList ();
            //转换成字符串
            String selectAnswer = String.join (",", selectAnswerList);
            examQuestion.setSelectAnswer (selectAnswer);
        }

        //当前登录账号
        String username = (String) session.getAttribute ("username");
        if (StrUtil.isNotEmpty (username)) {
            QueryWrapper<User> wrapper = new QueryWrapper<> ();
            wrapper.eq ("username", username);
            User user = userMapper.selectOne (wrapper);
            examQuestion.setUserId (user.getId ());
            questionMapper.insert (examQuestion);
            return ResponseBean.success (ContentBean.SavaSuccess);
        }

        return ResponseBean.error (ContentBean.SavaError);
    }

    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding ("utf-8");
        //String path = System.getProperty ("user.dir");
        //System.out.println (path);
        File file = ResourceUtils.getFile ("classpath:templates");
        String path = file.getPath ();
        // 从请求中获取文件名
        //String fileName = request.getParameter("fileName");
        // 创建输出流对象
        ServletOutputStream outputStream = response.getOutputStream ();
        String fileName = "录题模板.xls";
        //以字节数组的形式读取文件
        byte[] bytes = FileUtil.readBytes (path + File.separator + fileName);
        // 设置返回内容格式
        response.setContentType ("application/octet-stream");

        // 把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码
        // 中文不要太多，最多支持17个中文，因为header有150个字节限制。
        // 这一步一定要在读取文件之后进行，否则文件名会乱码，找不到文件
        fileName = new String (fileName.getBytes ("UTF-8"), "ISO8859-1");
        // 设置下载弹窗的文件名和格式（文件名要包括名字和文件格式）
        response.setHeader ("Content-Disposition", "attachment;filename=" + fileName);
        // 返回数据到输出流对象中
        outputStream.write (bytes);
        // 关闭流对象
        IoUtil.close (outputStream);
        // 文件存储路径
        //String path = "D:/fileupload/file/Template/";
    }

    public ResponseBean imports(MultipartFile file, String  username) throws IOException {
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", username);
        User user = userMapper.selectOne (wrapper);

        InputStream inputStream = file.getInputStream ();
        ExcelReader reader = ExcelUtil.getReader (inputStream);

        Map map = new HashMap ();
        map.put ("题目类型(单选题/多选题/判断题/简答题)", "typeName");
        map.put ("题干", "questionContent");
        map.put ("A选项(如果无选项则不填)", "optionA");
        map.put ("B选项(如果无选项则不填)", "optionB");
        map.put ("C选项(如果无选项则不填)", "optionC");
        map.put ("D选项(如果无选项则不填)", "optionD");
        map.put ("正确答案(单选题输入A、B、C、D四个选项中的一个,多选题输入多个选项,以英文逗号分隔,判断题输入正确/错误,简答题直接输入)", "answerMain");

        reader.setHeaderAlias (map);
        List<QuestionVo> questionVos = reader.readAll (QuestionVo.class);
        for (QuestionVo questionVo : questionVos) {
            List<String> strType = Arrays.asList ("判断题", "单选题", "多选题", "简答题");
            List<String> strAnswer = Arrays.asList ("A", "B", "C", "D");
            if (StrUtil.isBlank (questionVo.getTypeName ()) || !strType.contains (questionVo.getTypeName ().trim ())) {
                return ResponseBean.error ("题目类型输入有误");
            } else if (StrUtil.isBlank (questionVo.getQuestionContent ())) {
                return ResponseBean.error ("题干不能为空");
            } else if (StrUtil.isBlank (questionVo.getAnswerMain ())) {
                return ResponseBean.error ("正确答案不能为空");
            } else {
                if (questionVo.getTypeName ().trim ().equals ("单选题") || questionVo.getTypeName ().trim ().equals ("多选题")) {
                    if (StrUtil.isBlank (questionVo.getOptionA ()) || StrUtil.isBlank (questionVo.getOptionB ()) || StrUtil.isBlank (questionVo.getOptionC ()) || StrUtil.isBlank (questionVo.getOptionD ())) {
                        return ResponseBean.error ("单选题和多选题选项A、B、C、D不能为空");
                    }

                    if (questionVo.getTypeName ().trim ().equals ("单选题")) {
                        if (!strAnswer.contains (questionVo.getAnswerMain ().trim ())) {
                            return ResponseBean.error ("单选题正确答案有误");
                        }
                        //单选题导入
                        ExamQuestion examQuestion = new ExamQuestion ();
                        examQuestion.setUserId (user.getId ());
                        String questionContent = questionVo.getQuestionContent ();

                        questionContent = questionContent.replace (" ", "_");
                        examQuestion.setQuestionContent (questionContent);
                        examQuestion.setOptionA (questionVo.getOptionA ().trim ());
                        examQuestion.setOptionB (questionVo.getOptionB ().trim ());
                        examQuestion.setOptionC (questionVo.getOptionC ().trim ());
                        examQuestion.setOptionD (questionVo.getOptionD ().trim ());
                        examQuestion.setQuestionType (1);
                        examQuestion.setRadioAnswer (questionVo.getAnswerMain ().trim ());
                        questionMapper.insert (examQuestion);
                    }

                    if (questionVo.getTypeName ().trim ().equals ("多选题")) {
                        List<String> asList = Arrays.asList ((questionVo.getAnswerMain ().trim ()).split (","));
                        if (!strAnswer.containsAll (asList)) {
                            return ResponseBean.error ("多选题正确答案有误");
                        }
                        //多选题导入
                        ExamQuestion examQuestion = new ExamQuestion ();
                        examQuestion.setUserId (user.getId ());
                        String questionContent = questionVo.getQuestionContent ();
                        questionContent = questionContent.replace (" ", "_");
                        examQuestion.setQuestionContent (questionContent);
                        examQuestion.setOptionA (questionVo.getOptionA ().trim ());
                        examQuestion.setOptionB (questionVo.getOptionB ().trim ());
                        examQuestion.setOptionC (questionVo.getOptionC ().trim ());
                        examQuestion.setOptionD (questionVo.getOptionD ().trim ());
                        examQuestion.setQuestionType (2);
                        examQuestion.setSelectAnswer (questionVo.getAnswerMain ().trim ());
                        questionMapper.insert (examQuestion);
                    }
                } else {
                    if (questionVo.getTypeName ().trim ().equals ("判断题")) {
                        if (!questionVo.getAnswerMain ().trim ().equals ("正确") && !questionVo.getAnswerMain ().trim ().equals ("错误")) {
                            return ResponseBean.error ("判断题正确答案有误");
                        }
                        //导入判断题
                        ExamQuestion examQuestion = new ExamQuestion ();
                        examQuestion.setUserId (user.getId ());
                        String questionContent = questionVo.getQuestionContent ();
                        questionContent = questionContent.replace (" ", "_");
                        examQuestion.setQuestionContent (questionContent);
                        String answerMain = questionVo.getAnswerMain ();
                        examQuestion.setTrueFalse (answerMain.equals ("正确") ? 1 : 0);
                        examQuestion.setQuestionType (3);
                        questionMapper.insert (examQuestion);
                    }

                    if (questionVo.getTypeName ().trim ().equals ("简答题")) {
                        //导入简答题
                        ExamQuestion examQuestion = new ExamQuestion ();
                        examQuestion.setUserId (user.getId ());
                        String questionContent = questionVo.getQuestionContent ();
                        questionContent = questionContent.replace (" ", "_");
                        examQuestion.setQuestionContent (questionContent);
                        examQuestion.setAnswerContent (questionVo.getAnswerMain ());
                        examQuestion.setQuestionType (4);
                        questionMapper.insert (examQuestion);
                    }
                }


            }
        }

        return ResponseBean.success ("导入成功");
    }
}
